package munci.old.java;

import java.util.LinkedList;
import java.util.List;

import munci.old.know.Stack;
import munci.old.use.Tokens;


public class Signature {
	
	public static final Object RETURNS = new Object() {
		@Override public String toString() {return "--";}
	};

	public final Type[] types;
	public final String[] names;
	public final Type returns;
	
	public Signature(Stack stack) {
		Object[] values = stack.values();
		int len = values.length;
		if (len > 1 && values[len - 2] == RETURNS) {
			this.returns = (Type) values[len - 1];
			len -= 2;
		} else {
			this.returns = Type.VOID;
		}

		List<Type> types = new LinkedList<Type>();
		List<String> names = new LinkedList<String>();

		int i = 0;
		while (i < len) {
			types.add((Type) values[i++]);
			if (i < len && values[i] instanceof CharSequence) {
				names.add(values[i++].toString());
			} else {
				names.add(null);
			}
		}
		this.types = types.toArray(new Type[0]);
		this.names = names.toArray(new String[0]);
	}
	
	public Tokens toJava(String methodName) {
		Tokens toks = new Tokens();
		toks.lex(returns.toString());

		toks.add(methodName).add("(");
		
		for (int i = 0; i < types.length; i++) {
			if (i > 0) toks.add(",");
			toks.lex(types[i].toString());
			if (names[i] != null) {
				toks.add(names[i]);
			} else {
				toks.add("$" + i);
			}
		}
		return toks.add(")");
	}
}
